#ifndef GHOSTFUNCTION_H
#define GHOSTFUNCTION_H

#include "FileFunction.h"

#include "BasicConfig.h"

#include <QProcess>
#include <QColor>
#include <QPixmap>
#include <QPainter>
#include <QObject>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#if defined Q_WS_WIN
#include <windows.h>
#if defined VISUALSTUDIOCC_
#include <ddeml.h>
#endif
#endif
#include <QtCore>
#include <QSettings>
#include <QApplication>

#define _GSCACHE_ \
             QString("%1/.ghosti_CACHE/").arg(QDir::homePath())


extern inline QString getGSLinuxPath( QString apps = QString("gs") )
{
    QStringList potential_paths;
    potential_paths.append("/usr/local/bin");
    potential_paths.append("/sw/bin");   /* to use on mac as same */
    potential_paths.append("/opt/bin");
    QProcess *process = new QProcess(NULL);
    process->setReadChannelMode(QProcess::MergedChannels);
    QStringList env = process->systemEnvironment();
    env.replaceInStrings(QRegExp("^PATH=(.*)", Qt::CaseInsensitive), "PATH=\\1;"+potential_paths.join(";"));
    process->setEnvironment(env);
    
        process->start( QString("which") ,  QStringList() << apps , QIODevice::ReadOnly );
          if (!process->waitForFinished()) {
          return QString();
          } else {
              QString finder = process->readAll().trimmed();
              if (finder.endsWith(apps,Qt::CaseInsensitive)) {
                 ///////////// qDebug() << "### finder " <<  finder;
                return finder;  
              } else {
                return QString(); 
              }
          }
}



/* find gpl GhostScript path or exe */
extern inline QString getGSDefaultExeName()
{
	QString gsName;
    QString gVersion;
#if defined Q_WS_WIN
    QFileInfo Pinfo;
	// Try to locate GhostScript thanks to the qsetting
	 gsName = "gswin32c.exe";
     QSettings softs("HKEY_LOCAL_MACHINE\\Software",QSettings::NativeFormat);
     QStringList allsoftware = softs.childGroups();
     QStringList gsonly = allsoftware.filter(QRegExp("Ghostscript"));
     //////////qDebug() << "### gsonly " <<  gsonly;
         for (int i = 0; i < gsonly.size(); ++i) {
              const QString RealName = gsonly.at(i);  /* realpath */
                      if (RealName.contains("Ghostscript")) {
                       //////////qDebug() << "### soft " <<  RealName;
                       for(int e=1;e<99;e++)  {
                           /* check version 8 ++ 99 down */
                           gVersion = QString("8.%1").arg(100 - e);
                           if (softs.value(RealName+"/"+gVersion+"/GS_DLL").toString().size() > 6 ) {
                               Pinfo.setFile(softs.value(RealName+"/"+gVersion+"/GS_DLL").toString());
                               return gsName.prepend(Pinfo.absolutePath()+"/");
                           }
                           /* check version 7 ++ 99 down */
                           gVersion = QString("7.%1").arg(100 - e);
                           if (softs.value(RealName+"/"+gVersion+"/GS_DLL").toString().size() > 6 ) {
                               Pinfo.setFile(softs.value(RealName+"/"+gVersion+"/GS_DLL").toString());
                               return gsName.prepend(Pinfo.absolutePath()+"/");
                           }
                       }
               }
         }
    
    /* win not having GPL Ghostscript ! */
    gsName = "";  
    return gsName;         
#endif
#if defined Q_WS_MAC
         
         QString pathfinder = getGSLinuxPath(QString("gs"));  /* which  simple append systems path mac + linux */
         if (pathfinder.size() > 2 && pathfinder.endsWith("gs",Qt::CaseInsensitive)) {
          return pathfinder;
         }
         
     QStringList paths;
     paths << "/usr/local/bin/gs" << "/usr/bin/gs" << "/bin/gs" << "/sw/bin/gs" << "/opt/bin/gs";
         QFileInfo gsp; 
          for (int i = 0; i < paths.size(); ++i)  {
                  gsp.setFile (paths.at(i));
                  if (gsp.exists()) {
                   return paths.at(i);
                  }                      
          }
	gsName = "gs";
    return gsName;
#endif
#if defined Q_WS_X11
    return getGSLinuxPath(); 
#endif
         /* forum http://www.qtcentre.org/forum/f-qt-programming-2/t-qsettings-read-only-avaiable-10254.html */
}


/* find gpl GhostScript version  */
extern inline double getGSVersion()
{
        QProcess process;
        QString Stversion;
        bool ok;
        double GS_version = 0.00;
        QRegExp regExp1(" (\\d+)\\.(\\d+).*");
        process.setReadChannelMode(QProcess::MergedChannels);
        process.start( getGSDefaultExeName() ,  QStringList() << "-v");
          if (!process.waitForFinished()) {
          return GS_version;
          } else {
              QString pu = process.readAll();
              QStringList line1 = pu.split("\n");
              int pos1 = regExp1.indexIn(line1.at(0));  /* only first line */
              if (pos1 > 0) {
                        Stversion = QString("%1.%2").arg(regExp1.cap(1).toInt()).arg(regExp1.cap(2).toInt());
                        double GS_version = Stversion.toDouble(&ok);
                         if (ok && GS_version > 5) {
                         return GS_version;
                         }
              } else {
              return GS_version;
              }
          }
return GS_version;
}

/*
#define _GSCACHE_ \
             QString("%1/.ghosti_CACHE/").arg(QDir::homePath())
 remove dir after works 
*/

extern inline int callGS( const QStringList args )
{
   const QString startnow = QDir::currentPath();
   const QString GhostScriptPath = getGSDefaultExeName();
   QDir::setCurrent(_GSCACHE_);
   QString  cmd1 =  GhostScriptPath + " ";
   cmd1 += args.join(" ");
   int fax = -1;
   #if defined Q_WS_MAC
   fax = system(cmd1.toLocal8Bit());
   QDir::setCurrent(startnow);
   return fax;
   #endif
   QProcess *process = new QProcess(NULL);
   process->setReadChannelMode(QProcess::MergedChannels);
   process->start( GhostScriptPath ,  args , QIODevice::ReadOnly );
          if (!process->waitForFinished()) {
           fax = -1;
          } else {
            QString ghostcomment = process->readAll().trimmed();
            //////qDebug() << "ghostcomment-> " << ghostcomment; 
            fax = 0;
          }
          
   QDir::setCurrent(startnow);
   return fax;
}


/*
extern inline int Funzionaaaaaaa_______lGS( const QStringList args )
{
   const QString startnow = QDir::currentPath();
   QDir::setCurrent(_GSCACHE_);
   QString  cmd1 = getGSDefaultExeName() + " ";
   cmd1 += args.join(" ");
   int fax = -1;
   fax = system(cmd1.toLocal8Bit());
   QDir::setCurrent(startnow);
   return fax;
}
*/


extern inline QPixmap LoadPS( QString fn , const QString arguments_append = QString() )
{
	const QString pdfFile = PathConvert(fn);
    QChar letter('A' + (qrand() % 26));
    QDateTime timer1( QDateTime::currentDateTime() );
    const QString qttmpFile = _GSCACHE_+QString("%2_%1.png").arg( timer1.toString("yyyy-MM-dd-HH-mm-ss-zzz") ).arg(letter);
    QFileInfo fitmp(qttmpFile);
    const int VersionGS = getGSVersion();

    QFile lastaction(fitmp.absoluteFilePath());
    lastaction.remove();
    
	QPixmap pm;
	int ret = -1;
	QStringList args;
    
    if (arguments_append.size() > 3) {
    args.append(arguments_append); 
    }
    
    if (VersionGS >=8) {
    args.append("-sDEVICE=png16m");
    args.append("-dGraphicsAlphaBits=4");
    args.append("-r72");
    args.append("-o");
	args.append(fitmp.fileName());
    args.append(pdfFile);
    } else {
    args.append("-sDEVICE=pnggray");
    args.append("-r72x72");
    args.append("-sOutputFile="+fitmp.fileName());
    args.append("-q");
    args.append(pdfFile);
    }
	ret = callGS(args);
    //////////qDebug() << "### ret " << ret << " VersionGS->" << VersionGS;
	if (ret == 0)
	{
		   QPixmap tmpimage(fitmp.absoluteFilePath());
           lastaction.remove();
           return tmpimage;
	}
	return pm;
}




    /*
    version < 8
    args.append("-r72x72");
    args.append("-sOutputFile="+imageiosFileCache);
    args.append("-q");
    args.append(pdfFile);
    */




extern inline QPixmap LoadPDF(QString fn, int Page, int w )
{
	QString tmp, cmd1, cmd2;
	const QString pdfFile = PathConvert(fn);
	const QString tmpFile = PathConvert(QDir::homePath()+"/sctodaytmps.png");
    const QString qttmpFile = QDir::homePath()+"/sctodaytmps.png";
	QPixmap pm;
    tmp.setNum(Page);
	int ret = -1;
	tmp.setNum(Page);
	QStringList args;
    args.append("-sDEVICE=png16m");
    args.append("-r72");
    args.append("-dGraphicsAlphaBits=4");
    args.append("-o");
	args.append(tmpFile);
    args.append("-dFirstPage="+tmp);
	args.append("-dLastPage="+tmp);
	args.append(pdfFile);
	ret = callGS(args);
    ////////qDebug() << "### ret " << ret;
	if (ret == 0)
	{
		QPixmap tmpimage(qttmpFile);
        QPixmap penna = tmpimage.scaledToWidth(w);
        tmpimage.detach(); 
        QFile lastaction(qttmpFile);
        lastaction.remove();
        QPainter p;
		p.begin(&penna);
		p.setBrush(Qt::NoBrush);
		p.setPen(QPen(QBrush(Qt::black),2,Qt::SolidLine));
		p.drawRect(0, 0, penna.width(), penna.height());
		p.end();
        return penna;
	}
	return pm;
}




class Ui_Gui_About
{
public:
    QGridLayout *gridLayout;
    QHBoxLayout *hboxLayout;
    QLabel *label_3;
    QLabel *label;
    QLabel *label_2;
    QHBoxLayout *hboxLayout1;
    QPushButton *okButton;

    void setupUi(QDialog *Gui_About)
    {
    if (Gui_About->objectName().isEmpty())
        Gui_About->setObjectName(QString::fromUtf8("Gui_About"));
    QSize size(629, 391);
    size = size.expandedTo(Gui_About->minimumSizeHint());
    Gui_About->resize(size);
    QPalette palette;
    QBrush brush(QColor(0, 0, 0, 255));
    brush.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::WindowText, brush);
    QBrush brush1(QColor(236, 233, 216, 255));
    brush1.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Button, brush1);
    QBrush brush2(QColor(255, 255, 255, 255));
    brush2.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Light, brush2);
    QBrush brush3(QColor(241, 239, 226, 255));
    brush3.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Midlight, brush3);
    QBrush brush4(QColor(172, 168, 153, 255));
    brush4.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Dark, brush4);
    QBrush brush5(QColor(157, 155, 144, 255));
    brush5.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Mid, brush5);
    palette.setBrush(QPalette::Active, QPalette::Text, brush);
    palette.setBrush(QPalette::Active, QPalette::BrightText, brush2);
    palette.setBrush(QPalette::Active, QPalette::ButtonText, brush);
    palette.setBrush(QPalette::Active, QPalette::Base, brush2);
    palette.setBrush(QPalette::Active, QPalette::Window, brush2);
    QBrush brush6(QColor(113, 111, 100, 255));
    brush6.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Shadow, brush6);
    QBrush brush7(QColor(49, 106, 197, 255));
    brush7.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Highlight, brush7);
    palette.setBrush(QPalette::Active, QPalette::HighlightedText, brush2);
    QBrush brush8(QColor(0, 0, 255, 255));
    brush8.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Link, brush8);
    QBrush brush9(QColor(255, 0, 255, 255));
    brush9.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::LinkVisited, brush9);
    QBrush brush10(QColor(232, 232, 232, 255));
    brush10.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::AlternateBase, brush10);
    palette.setBrush(QPalette::Inactive, QPalette::WindowText, brush);
    palette.setBrush(QPalette::Inactive, QPalette::Button, brush1);
    palette.setBrush(QPalette::Inactive, QPalette::Light, brush2);
    palette.setBrush(QPalette::Inactive, QPalette::Midlight, brush3);
    palette.setBrush(QPalette::Inactive, QPalette::Dark, brush4);
    palette.setBrush(QPalette::Inactive, QPalette::Mid, brush5);
    palette.setBrush(QPalette::Inactive, QPalette::Text, brush);
    palette.setBrush(QPalette::Inactive, QPalette::BrightText, brush2);
    palette.setBrush(QPalette::Inactive, QPalette::ButtonText, brush);
    palette.setBrush(QPalette::Inactive, QPalette::Base, brush2);
    palette.setBrush(QPalette::Inactive, QPalette::Window, brush2);
    palette.setBrush(QPalette::Inactive, QPalette::Shadow, brush6);
    palette.setBrush(QPalette::Inactive, QPalette::Highlight, brush1);
    palette.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush);
    palette.setBrush(QPalette::Inactive, QPalette::Link, brush8);
    palette.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush9);
    palette.setBrush(QPalette::Inactive, QPalette::AlternateBase, brush10);
    QBrush brush11(QColor(118, 116, 108, 255));
    brush11.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush11);
    palette.setBrush(QPalette::Disabled, QPalette::Button, brush1);
    palette.setBrush(QPalette::Disabled, QPalette::Light, brush2);
    QBrush brush12(QColor(245, 244, 235, 255));
    brush12.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Disabled, QPalette::Midlight, brush12);
    palette.setBrush(QPalette::Disabled, QPalette::Dark, brush4);
    palette.setBrush(QPalette::Disabled, QPalette::Mid, brush5);
    palette.setBrush(QPalette::Disabled, QPalette::Text, brush11);
    palette.setBrush(QPalette::Disabled, QPalette::BrightText, brush2);
    palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush11);
    palette.setBrush(QPalette::Disabled, QPalette::Base, brush2);
    palette.setBrush(QPalette::Disabled, QPalette::Window, brush2);
    palette.setBrush(QPalette::Disabled, QPalette::Shadow, brush);
    palette.setBrush(QPalette::Disabled, QPalette::Highlight, brush7);
    palette.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush2);
    palette.setBrush(QPalette::Disabled, QPalette::Link, brush8);
    palette.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush9);
    palette.setBrush(QPalette::Disabled, QPalette::AlternateBase, brush10);
    Gui_About->setPalette(palette);
    Gui_About->setModal(true);
    gridLayout = new QGridLayout(Gui_About);
#ifndef Q_OS_MAC
    gridLayout->setSpacing(6);
#endif
#ifndef Q_OS_MAC
    gridLayout->setMargin(9);
#endif
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));

    gridLayout->addItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding), 0, 1, 1, 1);


    gridLayout->addItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding), 2, 0, 1, 1);

    hboxLayout = new QHBoxLayout();
#ifndef Q_OS_MAC
    hboxLayout->setSpacing(6);
#endif
#ifndef Q_OS_MAC
    hboxLayout->setMargin(0);
#endif
    hboxLayout->setObjectName(QString::fromUtf8("hboxLayout"));

    hboxLayout->addItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));

    label_3 = new QLabel(Gui_About);
    label_3->setObjectName(QString::fromUtf8("label_3"));
    label_3->setPixmap(QPixmap(QString::fromUtf8(":/img/about_as_image.png")));

    hboxLayout->addWidget(label_3);

    label = new QLabel(Gui_About);
    label->setObjectName(QString::fromUtf8("label"));
    label->setPixmap(QPixmap());

    hboxLayout->addWidget(label);

    label_2 = new QLabel(Gui_About);
    label_2->setObjectName(QString::fromUtf8("label_2"));
    label_2->setPixmap(QPixmap());

    hboxLayout->addWidget(label_2);


    hboxLayout->addItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));


    gridLayout->addLayout(hboxLayout, 1, 0, 1, 2);

    hboxLayout1 = new QHBoxLayout();
#ifndef Q_OS_MAC
    hboxLayout1->setSpacing(6);
#endif
    hboxLayout1->setMargin(0);
    hboxLayout1->setObjectName(QString::fromUtf8("hboxLayout1"));

    hboxLayout1->addItem(new QSpacerItem(131, 31, QSizePolicy::Expanding, QSizePolicy::Minimum));

    okButton = new QPushButton(Gui_About);
    okButton->setObjectName(QString::fromUtf8("okButton"));

    hboxLayout1->addWidget(okButton);


    gridLayout->addLayout(hboxLayout1, 3, 0, 1, 2);


    retranslateUi(Gui_About);
    QObject::connect(okButton, SIGNAL(clicked()), Gui_About, SLOT(accept()));

    QMetaObject::connectSlotsByName(Gui_About);
    } // setupUi

    void retranslateUi(QDialog *Gui_About)
    {
    Gui_About->setWindowTitle(QApplication::translate("Gui_About", "Dialog", 0, QApplication::UnicodeUTF8));
    label_3->setText(QString());
    label->setText(QString());
    label_2->setText(QString());
    okButton->setText(QApplication::translate("Gui_About", "OK", 0, QApplication::UnicodeUTF8));
    Q_UNUSED(Gui_About);
    } // retranslateUi

};

namespace Ui {
    class Gui_About: public Ui_Gui_About {};
} // namespace Ui










//
class Gui_About : public QDialog, public Ui::Gui_About
{
    Q_OBJECT
//
public: Gui_About( QWidget* = 0 )
{
 setupUi( this );
}
protected:
private:
signals:

public slots:

};

    
    
#endif // GHOSTFUNCTION_H

